package homework;

import java.sql.SQLOutput;
import java.util.Arrays;
import java.util.Scanner;

/*作业: 猜字母游戏
   1.生成 5 个随机的字母 char[]   char 比较可以用==
   2.用户猜字母 next()
   3.比较   正确答案:ERWAG   猜:ABCDE   结果:2个字母正确,其中位置正确的有0个
                猜:EABCD    结果:2个字母正确,其中位置正确的有1个
   4.输入byebye, 退出程序
   hz_liuzb@163.com
   邮件主题：2012周末班-姓名-day03作业
*/
public class GuessTheLetters {
    public static void main(String[] args) {
        char[] letter = answer();
        while (true) {

            System.out.println("正确字母"+Arrays.toString(letter));
            System.out.println("输入5个不重复的大写字母,输入byebye可退出程序：");
            Scanner sc = new Scanner(System.in);
            String guessLetter;
            guessLetter = sc.next();
            if ("byebye".equals(guessLetter))
                break;
            //toCharArray() 将String类型 转换成char类型
            char guessLetterChar[];
            guessLetterChar = guessLetter.toCharArray();
            int[] result = compare(letter, guessLetterChar);
            System.out.println(+result[0] + "个字母正确且" + result[1] + "个位置正确");
            if (result[1] == 5) {
                System.out.println("程序结束");
                break;
            }
        }
    }

    //生成5个字母的方法
    public static char[] answer() {
        char[] letter = new char[5];
        char[] letter_26 = new char[26];
        //生成26个大写字母
        for (int i = 0; i < letter_26.length; i++) {
            letter_26[i] = (char) (65 + i);
        }
        for (int i = 0; i < letter.length; i++) {
            int random = (int) (Math.random() * 26);
            letter[i] = letter_26[random];
            //生成不重复的5个字母
            for (int j = 0; j < i; j++)
                if (letter[i] == letter[j]) {
                    i--;
                    break;
                }
        }
        return letter;
    }

    //比较方法
    public static int[] compare(char[] guessLetterChar, char[] letter) {
        int[] result = new int[2];
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++)
                if (guessLetterChar[j] == letter[i]) {
                    result[0]++;
                    if (guessLetterChar[i] == letter[i])
                        result[1]++;
                }
        }
        return result;
    }

}
